/**
 * Created by user on 2015/9/28.
 */

var async = require('async');
var Question = mongoose.model('question');
var Goods = mongoose.model('goods');
var GoodsReply = mongoose.model('goods_reply');


exports.secondHandSyncService = function(req ,callback) {

    var body = req.body;

    var option =  {isValid:true,category:'secondhand'};

    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (body.startDate < body.endDate) {
                option.dateCreated = {$gte: body.startDate, $lte: body.endDate};
            }
        } else if (body.startDate) {
            option.dateCreated = {$gte: body.startDate};
        } else if (body.endDate) {
            option.dateCreated = {$lte: body.endDate};
        }

    };

    logger.debug(option);

    Question.find(option)
        .populate('community', 'communityName location cityId')
        .populate('aroundCommunity', '_id communityName')
        .populate('tag', 'value')
        .populate('createdBy', '_id nickName')
        .populate('replies.repliedBy', '_id community nickName images authenticationStatus')
        .exec(function (err, result) {

            async.eachSeries(result, function (question, callbackInner) {
                //logger.debug(question);
                var goods = {};
                goods.oldId = question._id
                goods.title = question.title;
                goods.desc = question.desc;
                goods.images = question.images;
                goods.community = question.community;
                goods.aroundCommunity = question.aroundCommunity;
                goods.city = question.community.cityId;
                if(question.community) {
                    if(question.community.location)
                    {
                        goods.location = {
                            longitude: question.community.location.longitude,
                            latitude: question.community.location.latitude
                        };
                        goods.locOrder = {
                            longitude: question.community.location.longitude.toFixed(4) + '' + (4000000000 - Math.round(new Date().getTime() / 1000)),
                            latitude: question.community.location.latitude
                        };
                    };
                };
                goods.isInit = 0;
                goods.createdBy = question.createdBy;
                goods.releaseDate = question.dateCreated;
                goods.dateLastModified = question.dateLastModified;
                goods.dateCreated = question.dateCreated;
                //logger.debug(goods);
                var temp = new Goods(goods);
                //logger.debug(temp);流
                var key = 'communityId:' + temp.community + ':around';
                //logger.debug(key)
                redisClient.SMEMBERS(key, function (err, value) {
                    temp.aroundCommunity = value;

                    temp.save(function (err, result) {
                        //保存browner、replyCount、collectionNum 数量
                        var goodsKey = "goods:" + result._id + ":detail";
                        var args = [
                            goodsKey,
                            'browner', question.browserCount ? question.browserCount : 0,
                            'replyCount', question.replies ? question.replies.length : 0,
                            'collectionNum',0
                        ];
                        redisClient.HMSET(args, function (err, res) {
                            logger.debug(goodsKey);
                            logger.debug(res);
                        });
                        if (question.replies && question.replies.length > 0) {
                            var goodsId = result._id;
                            async.eachSeries(question.replies, function (rep, callbackInner2) {

                                var reply = new GoodsReply();
                                reply.goodsId = goodsId;
                                reply.replyDesc = rep.replyDesc;
                                reply.community = rep.repliedBy.community;
                                reply.repliedBy = rep.repliedBy._id;
                                reply.dateReplied = rep.dateReplied;
                                //logger.debug(reply);
                                reply.save(callbackInner2);

                            }, function (err) {
                                callbackInner(err, null);
                            });
                        } else {
                            callbackInner();
                        };
                    });

                });
            }, function (err) {
                callback(err, null);
            })


        });

};
